package com.sheep.dynamic.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.sheep.dynamic.entity.DataSourceMeta;
import com.sheep.dynamic.mapper.DataSourceMetaMapper;
import com.sheep.dynamic.util.InitDBUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 数据源元数据服务
 *
 * @author 第七人格
 * @date 2023/04/13
 */
@Service
@DS("master")
public class DataSourceMetaService {

    /**
     * 数据源元映射器
     */
    @Resource
    private DataSourceMetaMapper datasourceMetaMapper;

    /**
     * 选择可用数据
     *
     * @param dataSourceMeta 数据源元
     * @return {@link List}<{@link DataSourceMeta}>
     */
    public List<DataSourceMeta> selectAvailable(DataSourceMeta dataSourceMeta) {
        return new LambdaQueryChainWrapper<>(datasourceMetaMapper)
                .eq(DataSourceMeta::getId, dataSourceMeta.getId())
                .eq(DataSourceMeta::getUrl, dataSourceMeta.getUrl())
                .list();
    }

    public void add(DataSourceMeta dataSourceMeta) {
        datasourceMetaMapper.insert(dataSourceMeta);
    }

    public void update(DataSourceMeta dataSourceMeta) {
        datasourceMetaMapper.updateById(dataSourceMeta);
    }

    public void delete(int dataSourceMetaId) {
        datasourceMetaMapper.deleteById(dataSourceMetaId);
    }

    public boolean initDB(DataSourceMeta dataSourceMeta) {
        return InitDBUtil.initDB(dataSourceMeta.getUrl(),dataSourceMeta.getMysqlSchema(),dataSourceMeta.getUsername(),dataSourceMeta.getPassword());
    }

    public boolean tryConnectDB(DataSourceMeta dataSourceMeta) {
        return InitDBUtil.tryConnectDB(dataSourceMeta.getUrl(),dataSourceMeta.getMysqlSchema(),dataSourceMeta.getUsername(),dataSourceMeta.getPassword());
    }
}
